package com.yitianyigexiangfa.coap.cbor.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import com.yitianyigexiangfa.coap.cbor.jackson.entity.User;
import com.yitianyigexiangfa.coap.cbor.util.ConvertUtil;

import java.io.IOException;

/**
 * @author Bill Lau
 * @date 2017-12-23
 */
public class JacksonObjectDemo {

    public static void main(String[] args) {
        CBORFactory f = new CBORFactory();
        ObjectMapper mapper = new ObjectMapper(f);
        User user = new User();
        user.setAge(18);
        user.setName("liubei");
        user.setHeight(18.2);

        // ================== 编码 ==================
        try {
            byte[] cborData = mapper.writeValueAsBytes(user);
            System.out.println(ConvertUtil.bytesToHex(cborData));

            // ================== 解码 ==================
            User resultUser = mapper.readValue(cborData, User.class);
            System.out.println(resultUser.toString());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
